import './App.css';
import React, {
  useState,
  useEffect
} from 'react';
const initList = [{
  name: '小刘',
  age: '25',
  sex: '男',
  job: '前端开发',
  key: 0
},
{
  name: '小王',
  age: '22',
  sex: '男',
  job: '前端实习',
  key: 1

},
{
  name: '小李',
  age: '28',
  sex: '女',
  job: '后端开发',
  key: 2
},
{
  name: '小美',
  age: '23',
  sex: '女',
  job: '',
  key: 3
},
{
  name: '老王',
  age: '29',
  sex: '男',
  job: 'UI设计师',
  key: 4
}]
const App = () => {
  const [list, setList] = useState([])
  const [searchValue, setSearchValue] = useState({ name: '', sex: '' })

  useEffect(() => {
    setList(initList)
  }, [])
  const columns = [{
    name: '姓名',
    key: 'name'
  },
  {
    name: '性别',
    key: 'sex'
  },
  {
    name: '年龄',
    key: 'age'
  },
  {
    name: '工作',
    key: 'job'
  }
  ]
  // 输入框改变
  const inputChange = (e) => {
    setSearchValue(prev => {
      let lastvalue = prev
      lastvalue.name = e.target.value
      return lastvalue
    })
  }
  // 性别框框改变
  const sexChange = (e) => {
    setSearchValue(prev => {
      let lastvalue = prev
      lastvalue.sex = e.target.value
      return lastvalue
    })
  }

  //搜索
  const searchNow = () => {
    let newList = [...initList]
    Object.keys(searchValue).forEach(searchItem => {
      if (searchValue[searchItem] !== '')
        newList = newList.filter(listItem => {
          if (searchItem === 'name') {
            return listItem[searchItem].indexOf(searchValue[searchItem]) !== -1
          } else {
            return listItem[searchItem] === searchValue[searchItem]
          }
        })
    })
    setList(newList)
  }

  return (
    <div>
      <div style={{ display: 'flex', marginTop: 50, marginLeft: 20 }}>
        <div>姓名：
          <input style={{ width: 100 }} onChange={inputChange}></input>
        </div>
        <div style={{ marginLeft: 10 }}>性别：
          <select onChange={sexChange}>
            <option value="">全部</option>
            <option value="男">男</option>
            <option value="女">女</option>
          </select>
        </div>

        <button style={{ marginLeft: 10 }} onClick={searchNow}>搜索</button>
      </div>
      <table style={{ marginTop: 20, marginLeft: 100 }} border="1">
        <thead>
          <tr>
            {columns.map(item =>
              <td key={item.key}>{item.name}</td>
            )}
          </tr>
        </thead>
        <tbody>
          {
            list.map(item =>
              <tr key={item.key}>
                {
                  columns.map(column =>
                    item[column.key] ? <td key={column.key}>{item[column.key]}</td> : <td key={column.key}>(无数据)</td>
                  )
                }
              </tr>
            )
          }
        </tbody>
      </table>
    </div>
  )
}

export default App;